<?php

require_once 'Pipes/Database/RelationshipTable.php';
require_once 'Pipes/FileSystem/Model/Finder.php';
require_once 'Pipes/Generator/Create/Controller.php';
require_once 'Pipes/Generator/Create/Model.php';
require_once 'Pipes/Generator/Create/ModelList.php';
require_once 'Pipes/Generator/Create/Model/Mapper.php';
require_once 'Pipes/Generator/Create/Model/Meta.php';
require_once 'Pipes/Generator/Create/View.php';
require_once 'PipesImpl/Config.php';

class Pipes_Generator_Create
{
	private $_creators = array();
	private $_default_options = array(
		'with' => array()
	);
	private $_options = array();
	private $_relatedObjects = array();
	private $_config = null;
	private $_projectPath = null;

	public function __construct(PipesImpl_Config $config, $projectPath, array $options = array()) {
		$this->_config = $config;
		$this->_projectPath = $projectPath;

		array_push($this->_creators,
			new Pipes_Generator_Create_Controller($projectPath),
			new Pipes_Generator_Create_Model($projectPath),
			new Pipes_Generator_Create_ModelList($projectPath),
			new Pipes_Generator_Create_Model_Mapper($projectPath),
			new Pipes_Generator_Create_Model_Meta($projectPath),
			new Pipes_Generator_Create_View($projectPath)
		);
	}
	
	public function create($name, array $options = array()) {
		foreach ($this->_creators as $creator) {
			$creator->create($name, $this->_options);
		}
		
		if (count($options) == 0) {
			return;
		}

		$relationshipCreator = new Pipes_Generator_Create($this->_config, $this->_projectPath);
		$relationshipFinder = new Pipes_FileSystem_Model_Finder($this->_config);
		foreach ($options['with'] as $related) {
			// create model if we can't find it
			try {
				$relationshipFinder->find($related);
			} catch (Pipes_Exception $e) {
				$relationshipCreator->create($related);
			}

			// create relationship table if it doesn't exist
			$relationshipTable = new Pipes_Database_RelationshipTable($this->_config, $name, $related);
			if (!$relationshipTable->exists()) {
				$relationshipTable->create();
			}
		}
	}
}
